<?php
/**
 * Created by PhpStorm.
 * User: caipeichao
 * Date: 14-3-11
 * Time: PM5:41
 */

namespace Admin\Controller;

use Admin\Builder\AdminConfigBuilder;
use Admin\Builder\AdminListBuilder;

class AppstoreController extends AdminController
{
    protected $mAdminListBuilder;
    protected $mGoodsModel;

    protected $codeModel;
    protected $codeTypeModel;
    protected $appstoreTypeModel;
    protected $appstoreGoodsModel;
    protected $appstoreVersionModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->mAdminListBuilder;
        $this->mGoodsModel = D('AppstoreGoods');
        $this->codeModel = D('Appstore/AppstoreCode');
        $this->codeTypeModel = D('Appstore/AppstoreCodeType');
        $this->appstoreTypeModel = D('Appstore/AppstoreType');
        $this->appstoreGoodsModel = D('Appstore/AppstoreGoods');
        $this->appstoreVersionModel = D('Appstore/AppstoreVersion');
    }

    public function index($page = 1, $r = 20, $content = '')
    {
        redirect(U('verify'));
    }

    public function shops($page = 1, $r = 20)
    {
        if(IS_POST){
            $aDo=I('get.do','','text');
            $aIds=I('post.ids',array(),'intval');
            if($aDo=='reset'){
                $result=D('Appstore/AppstoreShop')->resetShopData($aIds);
                if($result!==false){
                    $this->success('重置数据成功，共影响'.$result.'个店铺。');
                }else{
                    $this->error('重置数据失败。');
                }

            }

        }else{
            $listBuilder = new AdminListBuilder();
            $listBuilder->title('店铺列表');
            $lists = D('AppstoreShop')->where('status>-1')->page($page, $r)->select();
            $count = D('AppstoreShop')->where('status>-1')->count();
            foreach ($lists as &$v) {
                $v['id'] = $v['uid'];
                $status = array('0' => '<span class="text-muted">等待提交审核</span>', '2' => '<span class="text-danger">提交审核中</span>',
                    '3' => '<span class="text-warning">审核不通过</span>', '1' => '<span class="text-success">运营中</span>');
                $v['status_str'] = $status[$v['status']];
            }
            unset($v);
            $listBuilder->keyLink('title', '店名', 'shop?id=###')->keyBool('gold', '金牌店铺')->keyBool('official', '官方认证店铺')->keyText('star', '评级')->keyText('evaluation', '评定')->keyText('sales_count', '销量')->keyText('goods_count', '商品数量')->keyUid()->keyCreateTime()
                ->keyText('status_str', '审核状态');
            $listBuilder->data($lists);
            $listBuilder->pagination($count, $r);
            $listBuilder->ajaxButton(U('shops'), array('do' => 'reset'), '重置全部店铺数据',array('hide-data'=>'true'));
            $listBuilder->display();
        }

    }

    public function shop($id = 0)
    {
        $shopModel = D('AppstoreShop');
        if (IS_POST) {

            $shop = $shopModel->create();
            $old = $shopModel->find($shop['uid']);
            if ($old['status'] == 2) {
                if ($shop['status'] == 3) {
                    //审核不通过
                    D('Common/Message')->sendMessageWithoutCheckSelf($shop['uid'], '云市场开店审核未被通过', '您的店铺未能通过审核，未能通过审核的原因：' . $shop['suggestion'] . '，请在整改后再提交申请。', 'Appstore/Admin/shop');
                }
                if ($shop['status'] == 1) {
                    D('Common/Message')->sendMessageWithoutCheckSelf($shop['uid'], '店铺正式开通通知', '恭喜您，您在云市场提交的开店申请已被批准，店铺正式开通。', 'Appstore/Index/shop', array('id' => $shop['uid']));
                    $weibo_content = '云市场通告：开发者[at:' . $shop['uid'] . ']的新店铺《' . $shop['title'] . '》开张，快去看看吧：' . U('Appstore/Index/shop', array('id' => $shop['uid']), null, true);
                    $feed_data['attach_ids'] = $old['logo'];
                    $result = D('Weibo/Weibo')->addWeibo(is_login(), $weibo_content, 'image', $feed_data, '云市场');


                    //审核通过
                }
            }
            $result = $shopModel->save($shop);

            if ($result === false) {
                $this->error('编辑失败。');
            } else {
                $this->success('编辑成功。');
            }
            exit;
        } else {
            $configBuilder = new AdminConfigBuilder();
            $data = $shopModel->find($id);
            $configBuilder->keyUid('uid', '店铺所有者ID')->title('编辑店铺')->keyTitle()->keyBool('gold', '金牌店铺')->keyBool('official', '官方认证店铺')->keyText('star', '评级')->keyText('evaluation', '评定')
                ->keySelect('status', '审核状态', '审核状态', array('0' => '等待提交审核', '2' => '提交审核中', '3' => '审核不通过', '1' => '运营中'))
                ->keyText('suggestion', '审核意见', '拒绝审核的话，必须填写审核意见');
            $configBuilder->data($data);
            $configBuilder->buttonSubmit();
            $configBuilder->display();
        }


    }

    public function goods($page = 1, $r = 20)
    {
        //TODO 支持搜索
        $this->mAdminListBuilder = new AdminListBuilder();
        $goods = $this->mGoodsModel->where('status > -1')->page($page, $r)->select();
        $count = $this->mGoodsModel->where('status > -1')->count();

        $this->mAdminListBuilder->title('商品审核')
            ->buttonSetStatus(U('Appstore/setStatus'), 2, '设为待审核', array())
            ->search('搜索', 'title', null, '支持标题')
            ->keyLink('title', '名称', 'appstore/index/goodsdetail?id=###')->keyUid()->keyCreateTime()->keyUpdateTime()
            ->data($goods)->pagination($count, $r)->display();
    }

    /**审核商品
     * @param int $page
     * @param int $r
     * @auth 陈一枭
     */
    public function verify($page = 1, $r = 20)
    {
        //TODO 支持搜索
        $this->mAdminListBuilder = new AdminListBuilder();
        $goods = $this->mGoodsModel->where(array('status' => 2))->page($page, $r)->select();


        $this->mAdminListBuilder->title('商品审核')
            ->buttonSetStatus(U('Appstore/setStatus'), 1, '审核通过', array())
            ->search('搜索', 'title', null, '支持标题')
            ->keyLink('title', '名称', 'appstore/index/goodsdetail?id=###')->keyUid()->keyCreateTime()->keyUpdateTime()
            ->data($goods)->display();
    }

    public function type($page = 1, $r = 20)
    {
        $entity = I('entity', 0, 'intval');
        if ($entity != 0) {
            $map['entity'] = $entity;
        }

        $builder = new AdminListBuilder();
        $builder->title('商品分类管理');
        $list = D('Appstore/AppstoreType')->getList($map, $r, 'id desc');

        foreach ($list['data'] as &$v) {
            switch ($v['entity']) {
                case 1:
                    $v['entity_alias'] = '插件';
                    break;
                case 2:
                    $v['entity_alias'] = '模块';
                    break;
                case 3:
                    $v['entity_alias'] = '模板';
                    break;
                case 4:
                    $v['entity_alias'] = '服务';
                    break;
            }
        }
        unset($v);
        $builder->keyId()->keyLink('title', '分类名称', 'addType?id=###')->keyText('entity_alias', '分类所属');
        $builder->setSelectPostUrl(U('type'))->select('', 'entity', 'select', '', '', '', array(array('id' => 0, 'value' => '全部'), array('id' => 1, 'value' => '插件'), array('id' => 2, 'value' => '模块'), array('id' => 3, 'value' => '主题'), array('id' => 4, 'value' => '服务')));;
        $builder->buttonNew(U('addType', array('entity' => $entity)), '新增');
        $builder->data($list[data]);

        $builder->display();
    }

    public function addType()
    {
        if (IS_POST) {
            $aId = I('post.id', 0, 'intval');
            $aTitle = I('title', '', 'text');
            $aEntity = I('entity', 1, 'intval');
            $aSort = I('sort', 0, 'intval');
            $aTitle = $aTitle == '' ? $this->error('分类名称必填') : $aTitle;
            $data['title'] = $aTitle;
            $data['sort'] = $aSort;
            $data['entity'] = $aEntity;
            $data['status'] = 1;
            if ($aId != 0) {
                //存储
                $data['id'] = $aId;
                $rs = M('AppstoreType')->save($data);
            } else {
                $rs = M('AppstoreType')->add($data);
            }
            if ($rs === false) {

                $this->error('保存失败。');
            } else {
                $this->success('保存成功。');
            }

        } else {
            $id = I('id', 0, 'intval');
            if ($id != 0) {
                $data = M('AppstoreType')->find($id);
            } else {
                $entity = I('entity', 1, 'intval');

                if ($entity == 0) {
                    $entity = 1;
                }
                $data['entity'] = $entity;
                $data['status'] = 1;
                $data['sort'] = 0;
            }

            $builder = new AdminConfigBuilder();

            $builder->title('新增分类');
            $builder->keyId();
            $builder->keyTitle();
            $builder->keyRadio('entity', '分类所属', '', array('1' => '插件', 2 => '模块', '3' => '主题', 4 => '服务'))
                ->keyInteger('sort', '排序')
                ->keyStatus();
            $builder->data($data)->buttonSubmit();

            $builder->display();
        }


    }

    /**
     * @auth 陈一枭
     */
    public function trash($page = 1, $r = 20)
    {
        $this->mAdminListBuilder = new AdminListBuilder();
        $goods = $this->mGoodsModel->where(array('status' => -1))->page($page, $r)->select();


        $this->mAdminListBuilder->title('商品审核')
            ->buttonSetStatus(U('Appstore/setStatus'), 1, '审核通过', array())
            ->search('搜索', 'title', null, '支持标题')
            ->keyLink('title', '名称', 'appstore/edit?id=###')->keyUid()->keyCreateTime()->keyUpdateTime()
            ->data($goods)->display();
    }


    /**设置商品状态，用于审核通过
     * @param int $ids id，表单自动获取
     * @param int $status 默认为正常状态1
     * @auth 陈一枭
     */
    public function setStatus($ids = 0, $status = 1)
    {
        if ($ids == 0) {
            $this->error('请选择商品');
        }
        $appstoreModel = D('AppstoreGoods');
        $weiboModel = D('Weibo/weibo');
        $map['id'] = array('in', implode(',', $ids));
        $rs = $this->mGoodsModel->where($map)->setField('status', $status);
        if ($status == 1) {
            foreach ($ids as $id) {
                $goods = $appstoreModel->find($id);
                $user = query_user(array('nickname'), $goods['uid']);
                $weibo_content = '管理员审核通过了@' . $user['nickname'] . ' 的商品：【' . op_t($goods['title']) . '】，快去看看吧：' . "http://$_SERVER[HTTP_HOST]" . U('appstore/index/goodsDetail', array('id' => $goods['id']));
                $weiboModel->addWeibo(is_login(), $weibo_content, 'feed', null, '云市场');
            }
        }

        $this->success('成功设置' . $rs . '件商品的状态。');
    }

    public function marketing()
    {
        $builder = new AdminConfigBuilder();
        $data = $builder->handleConfig();

        $builder->title('营销设置');
        $builder->keyText('RECOMMOND_SHOPS', '优质服务商', 'ID,逗号分隔，按顺序，最多4个');
        $builder->keyText('RECOMMOND_PLUGINS', '推荐插件', 'ID,逗号分隔，按顺序，最多4个');
        $builder->keyText('RECOMMOND_MODULES', '推荐模块', 'ID,逗号分隔，按顺序，最多4个');
        $builder->keyText('RECOMMOND_THEMES', '推荐主题', 'ID,逗号分隔，按顺序，最多4个');
        $builder->keyText('RECOMMOND_SERVICES', '推荐服务', 'ID,逗号分隔，按顺序，最多4个');

        $builder->buttonSubmit();
        $builder->data($data)->keyDefault('RECOMMOND_DEVELOPER', '1');
        $builder->display();
    }

    public function ppt()
    {
        $list = M('AppstorePpt')->where(array('status' => array('gt', -1)))->select();
        $builder = new AdminListBuilder();
        $builder->title('首页PPT管理');
        $builder->buttonNew(U('addppt'))->setStatusUrl(U('Appstore/setPptStatus'))->buttonEnable()->buttonDisable()->buttonDelete();
        $builder->keyId()->keyLink('title', '标题', 'addppt?id=###')->keyImage('thumb', '小图')->keyImage('image', '大图')->keyTime('end_time', '截止日期')->keyText('url', '链接地址')->keyStatus();
        $builder->data($list);
        $builder->display();
    }

    public function setPptStatus($status)
    {
        $ids = I('ids');
        !is_array($ids) && $ids = explode(',', $ids);
        $builder = new AdminListBuilder();
        $builder->doSetStatus('AppstorePpt', $ids, $status);
    }

    public function addppt()
    {
        $pptModel = M('AppstorePpt');
        if (IS_POST) {
            $data = $pptModel->create();
            if (empty($data['id'])) {
                $rs = $pptModel->add($data);
            } else {
                $rs = $pptModel->save($data);
            }
            if ($rs === false) {
                $this->error('保存失败。');
            } else {
                $this->success('保存成功。');
            }
        } else {
            if (I('id')) {
                $default = $pptModel->find(I('id'));
            } else {
                $default['end_time'] = strtotime('2020-8-8');
                $default['sort'] = 1;
                $default['open_window'] = 1;
                $default['status'] = 1;
            }
            $builder = new AdminConfigBuilder();
            $builder->title('编辑幻灯片');
            $builder->keyId('id')->keyTitle('title', '标题')->keySingleImage('thumb', '小图,60*60,100*100')->keySingleImage('image', '大图,700*320')->keyTime('end_time', '截止时间', '超过截止时间就会被下架')->keyText('url', 'Url链接')
                ->keyText('sort', '排序，越大越靠前')
                ->keyBool('open_window', '新窗口打开')
                ->keyStatus();
            $builder->buttonSubmit();
            $builder->data($default);
            $builder->display();
        }

    }

    //zzl 云码 start

    /**
     * 云码类型列表
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function codeType()
    {
        $list = $this->codeTypeModel->getList(array('status' => array('egt', 0)));
        $builder = new AdminListBuilder();
        $builder->title('云码类型列表')
            ->setStatusUrl(U('Appstore/setCodeTypeStatus'))
            ->buttonNew(U('Appstore/editCodeType'))
            ->buttonEnable()->buttonDisable()->buttonDelete()
            ->keyId()
            ->keyTitle()
            ->keyText('versions', '绑定产品版本')
            ->keyText('length', '云码长度')
            ->keyStatus()
            ->keyCreateTime()
            ->keyDoActionEdit('Appstore/editCodeType?id=###')
            ->data($list)
            ->display();
    }

    /**
     * 编辑云码类型
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function editCodeType()
    {
        $aId = I('id', 0, 'intval');
        $title = $aId ? "编辑" : "新增";
        if (IS_POST) {
            $aTitle = $data['title'] = I('post.title', '', 'text');
            $aVersion_id = $data['version_ids'] = I('post.version_ids', '', 'text');
            $aLength = $data['length'] = I('post.length', 11, 'intval');
            $data['status'] = I('post.status', 1, 'intval');

            if (!mb_strlen($aTitle, 'utf-8')) {
                $this->error('请输入标题！');
            }
            if (!mb_strlen($aVersion_id, 'utf-8')) {
                $this->error('请选择绑定产品！');
            }
            if ($aLength < 6) {
                $this->error('为了安全，云码长度必须为6为以上！');
            }
            $data['version_id'] = implode(',', array_unique(explode(',', $data['version_id'])));
            if ($aId) {
                $data['id'] = $aId;
            }
            $result = $this->codeTypeModel->editData($data);
            if ($result) {
                $this->success("{$title}成功！", U('Appstore/codeType'));
            } else {
                $this->error("{$title}失败！" . $this->codeTypeModel->getError());
            }
        } else {
            $this->assign('top_title', $title);
            if ($aId) {
                $data = $this->codeTypeModel->getData($aId);
                $this->assign('data', $data);
            }
            $this->display(T('Application://Appstore@Appstore/editcodetype'));
        }
    }

    public function setCodeTypeStatus($ids, $status = 1)
    {
        !is_array($ids) && $ids = explode(',', $ids);
        if ($status == -1 || $status == 0) {
            $this->codeModel->where(array('type_id' => array('in', $ids), 'status' => array('neq', 2)))->setField('status', $status);
        }
        $builder = new AdminListBuilder();
        $builder->doSetStatus('AppstoreCodeType', $ids, $status);
    }

    /**
     * 云码列表页
     * @param int $page
     * @param int $r
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function code($page = 1, $r = 20)
    {
        $aStatus = I('status', -1, 'intval');
        if ($aStatus == -1) {
            $map['status'] = array('egt', 0);
            $_GET['status'] = -1;
        } else {
            $map['status'] = $aStatus;
        }
        list($list, $totalCount) = $this->codeModel->getList($map, $page, $r);

        $this->assign('list', $list);
        //生成翻页HTML代码
        C('VAR_PAGE', 'page');
        $pager = new \Think\Page($totalCount, $r, $_REQUEST);
        $pager->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $paginationHtml = $pager->show();
        $this->assign('pagination', $paginationHtml);
        $this->display(T('Application://Appstore@Appstore/codelist'));
    }

    public function codeUse($page = 1, $r = 20)
    {
        $codeUseModel = D('AppstoreCodeUse');
        $totalCount = $codeUseModel->count();
        $list = $codeUseModel->order('id desc')->page($page, $r)->select();
        foreach ($list as &$val) {
            $code = $this->codeModel->find($val['code_id']);
            $val['code'] = $code['code'];
            $val['code_title'] = '[' . $val['code_id'] . '] ' . $code['title'];
        }
        unset($val);
        $builder = new AdminListBuilder();
        $builder->title('云码使用记录')
            ->keyId()
            ->keyUid()
            ->keyText('code_title', '[云码id] 云码标题')
            ->keyText('code', '云码')
            ->keyCreateTime('create_time', '使用时间')
            ->data($list)
            ->pagination($totalCount, $r)
            ->display();
    }


    /**
     * 生成云码
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function createCode()
    {
        if (IS_POST) {
            $data['type_id'] = I('post.type_id', 0, 'intval');
            $aCodeNum = I('post.code_num', 0, 'intval');
            $type = $this->codeTypeModel->getData($data['type_id']);
            if (!$type['length']) {
                $result['status'] = 0;
                $result['info'] = '请选择云码类型！';
            }
            if ($aCodeNum <= 0) {
                $result['status'] = 0;
                $result['info'] = '生成个数不能小于1！';
            } else {
                $result = $this->codeModel->createCode($data, $aCodeNum, $type['length']);
            }
            $this->ajaxReturn($result);
        } else {
            $type_list = $this->codeTypeModel->getList(array('status' => 1));
            $this->assign('type_list', $type_list);
            $this->display(T('Application://Appstore@Appstore/create'));
        }
    }

    public function setCodeStatus($ids, $status = 1)
    {
        !is_array($ids) && $ids = explode(',', $ids);
        $id = array_unique((array)$ids);
        $rs = M('AppstoreCode')->where(array('id' => array('in', $id), 'status' => array('neq', 2)))->save(array('status' => $status));
        if ($rs === false) {
            $this->error('设置失败。');
        }
        $this->success('设置成功', $_SERVER['HTTP_REFERER']);
    }

    /**
     * 根据类型（模板、主题、插件、服务）获取分类列表
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function getCategoryByType()
    {
        $aType = I('post.type', 0, 'intval');
        $map['entity'] = $aType;
        $map['status'] = 1;
        $list = $this->appstoreTypeModel->getCategoryList($map);
        if (count($list)) {
            $html = '<option value="0">请选择分类</option>';
            foreach ($list as $val) {
                $html .= '<option value="' . $val['id'] . '">' . $val['title'] . '</option>';
            }
            $msg['html'] = $html;
            $msg['status'] = 1;
        } else {
            $msg['status'] = 0;
        }
        $this->ajaxReturn($msg);
    }

    /**
     * 根据商品分类id获取商品列表
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function getGoodsByCategory()
    {
        $aCategory = I('post.category', 0, 'intval');
        $map['type_id'] = $aCategory;
        $map['status'] = 1;
        $list = $this->appstoreGoodsModel->getGoodsList($map);
        if (count($list)) {
            $html = '<option value="0">请选择商品</option>';
            foreach ($list as $val) {
                $html .= '<option value="' . $val['id'] . '">' . $val['title'] . '</option>';
            }
            $msg['html'] = $html;
            $msg['status'] = 1;
        } else {
            $msg['status'] = 0;
        }
        $this->ajaxReturn($msg);
    }

    /**
     * 根据商品id获取版本列表
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function getVersionByGoods()
    {
        $aGoods = I('post.goods', 0, 'intval');
        $map['goods_id'] = $aGoods;
        $map['status'] = 1;
        $list = $this->appstoreVersionModel->getVersionList($map);
        $html = '<option value="0">请选择版本</option>';
        foreach ($list as $val) {
            $html .= '<option value="' . $val['id'] . '">' . $val['title'] . (floatval($val['need_buy']) ? '【收费】' : '【free】') . '</option>';
        }
        $msg['html'] = $html;
        $msg['status'] = 1;
        $this->ajaxReturn($msg);
    }

    /**
     * 导出cvs
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function cvs()
    {
        $aIds = I('ids', array());

        if (count($aIds)) {
            $map['id'] = array('in', $aIds);
        } else {
            $map['status'] = array('in', array(1, 0, -1));
            $dataListBack = $this->codeModel->getListAll(array('status' => 2));
        }
        $dataList = $this->codeModel->getListAll($map, 'status desc,id desc');
        if (!count($dataList) && !count($dataListBack)) {
            $this->error('没有数据！');
        }
        if (count($dataListBack)) {
            if (count($dataList)) {
                $dataList = array_merge($dataList, $dataListBack);
            } else {
                $dataList = $dataListBack;
            }
        }
        $data = "id,云码,标题,创建者,绑定产品,创建时间,当前状态\n";
        foreach ($dataList as $val) {
            if ($val['status'] == -1) {
                $val['status'] = "管理员删除";
            } elseif ($val['status'] == 2) {
                $val['status'] = "已使用";
            } elseif ($val['status'] == 1) {
                $val['status'] = "可用";
            } elseif ($val['status'] == 0) {
                $val['status'] = "禁用";
            }
            $val['create_time'] = time_format($val['create_time']);
            $data .= $val['id'] . "," . $val['code'] . "," . $val['title'] . "," . $val['user'] . "," . $val['versions'] . "," . $val['create_time'] . "," . $val['status'] . "\n";
        }
        $data = iconv('utf-8', 'gb2312', $data);
        $filename = '云码-' . date('Ymd') . '.csv'; //设置文件名
        $this->export_csv($filename, $data); //导出
    }

    private function export_csv($filename, $data)
    {
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        header("Content-type:application/vnd.ms-excel;charset=utf-8");
        echo $data;
    }

    //zzl 云码 end

    public function version()
    {
        $listBuilder = new AdminListBuilder();
        $listBuilder->title('版本管理');
        $data = M('AppstoreWebsiteVersion')->order('number desc')->select();
        foreach ($data as &$v) {
            $v['log'] = mb_substr($v['log'], 0, 40, 'utf-8');
        }

        $listBuilder->keyText('number', '编号')->keyLink('title', '版本名', 'addVersion?name={$name}')->keyText('name', '版本号')->keyCreateTime()->keyUpdateTime()->keyText('log', '更新日志')->keyHtml('url', '更新文章');
        $listBuilder->buttonNew(U('addVersion'));

        $listBuilder->data($data);
        $listBuilder->display();
    }

    public function addVersion()
    {
        $versionModel = M('AppstoreWebsiteVersion');
        if (IS_POST) {
            $version = $versionModel->create();
            $aName = I('post.name', '', 'text');
            $has = $versionModel->where(array('name' => $aName))->find();
            if ($has) {
                $rs = $versionModel->save($version);
                if ($rs === false) {
                    $this->error('版本保存失败。');
                } else {
                    $this->success('版本保存成功。');
                }
            } else {
                $rs = $versionModel->add($version);
                if ($rs === false) {
                    $this->error('版本添加失败。');
                } else {
                    $this->success('版本添加成功。');
                }
            }


        } else {
            $aName = I('get.name', '', 'text');
            if ($aName) {
                $data = $versionModel->where(array('name' => $aName))->find();
            }
            $configBuilder = new AdminConfigBuilder();
            $configBuilder->title('发布新版本');
            $configBuilder->keyText('number', '版本编号', '20150520');
            $configBuilder->keyTitle()->keyText('name', '版本号', '2.0.0')->keyTextArea('log', '更新日志')->keyText('url', '文章链接')
                ->keySingleFile('old_file', '老版文件包', '存放导出的老版本的文件包，主要用于比较差异')->keySingleFile('new_file', '新版文件包', '用于更新的文件包')
                ->keyCreateTime()->keyUpdateTime()->keyDefault('number', date('Ymd', time()));
            $configBuilder->buttonSubmit()->buttonBack()->data($data);
            $configBuilder->display();
        }

    }

    public function website($page = 1, $r = 20)
    {
        if (IS_POST) {
            $aIds = (array)I('post.ids', '', 'intval');
            $aStatus = I('get.status', 1, 'intval');
            if ($aStatus == -2) {
                $rs = D('AppstoreWebsite')->where(array('uid' => array('in', $aIds)))->delete();
            } else {
                $rs = D('AppstoreWebsite')->where(array('uid' => array('in', $aIds)))->setField('status', $aStatus);
            }

            if ($rs === false) {
                $this->error('设置失败，数据库操作失败。');
            } else {
                $this->success('设置成功，共影响了' . $rs . '个网站。');
            }

        } else {
            $websiteModel = D('AppstoreWebsite');
            $data = $websiteModel->order('create_time desc ')->page($page, $r)->select();
            $count = $websiteModel->order('create_time desc ')->count();
            $adminListBuilder = new AdminListBuilder();
            foreach ($data as &$v) {
                $v['id'] = $v['uid'];
                $v['title'] = '<a href="http://' . $v['domain'] . '" target="_blank">' . $v['title'] . '</a>';
                $v['domain'] = '<a href="http://' . $v['domain'] . '" target="_blank">' . $v['domain'] . '</a>';

            }
            unset($v);
            $adminListBuilder->keyId()->keyUid()->title('网站列表')->keyHtml('domain', '网站域名')->keyHtml('title', '网站名')->keyText('master', '持有人')->keyCreateTime()->keyStatus()->data($data)->pagination($count, $r);
            $adminListBuilder->buttonEnable(U('website'))->buttonSetStatus(U('website'), 0, '禁用', null)->buttonSetStatus(U('website'), -1, '删除', null)->buttonSetStatus(U('website'), -2, '彻底删除！', null);

            $adminListBuilder->display();
        }

    }

    public function developer($page = 1, $r = 20)
    {
        $developerModel = D('AppstoreDeveloper');
        $data = $developerModel->where(array('name' => array('neq', '')))->page($page, $r)->select();
        $count = $developerModel->where(array('name' => array('neq', '')))->count();
        $adminListBuilder = new AdminListBuilder();
        $adminListBuilder->title('开发者列表')->keyUid()->keyText('qq', 'QQ')->keyText('des', '介绍')->keyText('phone', '电话')->keyText('goodat', '擅长')->keyText('name', '姓名')->data($data)->pagination($count, $r);
        $adminListBuilder->display();
    }


    public function order()
    {
        $aPage = I('page', 1, 'intval');
        $aId = I('get.id', 0);

        $aVersionId = I('get.version_id', 0, 'intval');
        $aGoodsId = I('get.goods_id', 0, 'intval');

        if (!isset($_GET['status'])) {
            $_GET['status'] = -1;
        }
        if (!isset($_GET['pay_ok'])) {
            $_GET['pay_ok'] = -1;
        }
        $aStatus = intval($_GET['status']);
        $aPayOk = intval($_GET['pay_ok']);

        $r = 20;
        $orderModel = D('Appstore/AppstoreOrder');
        $map = array();
        $aId && $map['id'] = array('like', '%' . $aId . '%');

        $aVersionId && $map['version_id'] = $aVersionId;
        $aGoodsId && $map['goods_id'] = $aGoodsId;


        $aStatus != -1 && $map['status'] = $aStatus;
        $aPayOk != -1 && $map['pay_ok'] = $aPayOk;
        $data = $orderModel->where($map)->order('create_time desc')->page($aPage, $r)->select();

        foreach ($data as &$v) {
            $goods = $this->appstoreGoodsModel->getById($v['goods_id']);
            $v['goods'] = '[' . $v['goods_id'] . ']' . $goods['title'];
            $version = $this->appstoreVersionModel->getVersion($v['version_id']);
            $v['version'] = '[' . $v['version_id'] . '] V' . $version['title'];
            $v['status'] = $v['status'] ? '正常' : '<span class="text-danger">已取消</span>';
            $v['pay_ok'] = $v['pay_ok'] ? '<span class="text-success">已支付</span>' : '<span class="text-danger">未支付</span>';

            $score = D('Ucenter/Score')->getType(array('id' => $v['score']));
            $v['score'] = '[' . $v['score'] . ']' . $score['title'];
            $v['payment_price'] = $v['payment_price'] . $score['unit'];
        }
        unset($v);

        $count = $orderModel->where($map)->count();
        $adminListBuilder = new AdminListBuilder();
        $adminListBuilder->title('订单列表')
            ->keyId()
            ->keyUid()
            ->keyText('goods', '商品')
            ->keyText('version', '版本')
            ->keyText('status', '状态')
            ->keyCreateTime()
            ->keyText('score', '积分类型')
            ->keyText('payment_price', '支付数量')
            ->keyText('pay_ok', '支付状态')
            ->keyTime('pay_time', '支付时间')
            ->search('订单号', 'id')
            ->search('用户ID', 'uid')
            ->search('商品ID', 'goods_id')
            ->search('版本ID', 'version_id')
            ->setSearchPostUrl(U('Admin/appstore/order'))
            ->data($data)
            ->pagination($count, $r);

        $adminListBuilder->setSelectPostUrl(U('appstore/order'))
            ->select('状态：', 'status', 'select', '根据订单状态筛选', '', '', array(array('id' => -1, 'value' => '全部'), array('id' => 0, 'value' => '已取消'), array('id' => 1, 'value' => '正常')))
            ->select('支付状态：', 'pay_ok', 'select', '根据订单支付状态筛选', '', '', array(array('id' => -1, 'value' => '全部'), array('id' => 0, 'value' => '未支付'), array('id' => 1, 'value' => '已支付')));

        $adminListBuilder->display();


    }

}
